package com.promise.jokerdream.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.TextRange
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import android.view.View
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.ui.platform.LocalContext
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppFontSizes
import androidx.compose.runtime.rememberCompositionContext
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.ui.platform.LocalContext
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.DisposableEffect
import com.promise.jokerdream.ui.components.AppChip

/**
 * 多选Hashtag输入半浮层
 */
@Composable
fun MultiSelectHashtagBottomSheet(
    modifier: Modifier = Modifier,
    title: String = "选择标签",
    initialTags: List<String> = emptyList(),
    placeholder: String = "输入标签，回车添加",
    recommendedTags: List<String> = emptyList(),
    onCancel: () -> Unit,
    onComplete: (List<String>) -> Unit,
    onDismiss: (() -> Unit)? = null
) {
    val compositionContext = rememberCompositionContext()
    
    // 创建 PMBottomSheetDialog
    val pmDialog = pmBottomSheetDialog(onDismiss = onDismiss)
    
    // 设置 Compose 内容
    pmDialog.setContent(compositionContext) {
        MaterialTheme {
            MultiSelectHashtagBottomSheetContent(
                title = title,
                initialTags = initialTags,
                placeholder = placeholder,
                recommendedTags = recommendedTags,
                onCancel = {
                    onCancel()
                    pmDialog.dismiss()
                },
                onComplete = { tags ->
                    onComplete(tags)
                    pmDialog.dismiss()
                },
                onDismiss = onDismiss ?: {},
                modifier = modifier
            )
        }
    }

    // 显示对话框
    LaunchedEffect(Unit) {
        pmDialog.show()
    }

    // 清理资源
    DisposableEffect(Unit) {
        onDispose {
            pmDialog.dismiss()
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun MultiSelectHashtagBottomSheetContent(
    title: String,
    initialTags: List<String>,
    placeholder: String,
    recommendedTags: List<String>,
    onCancel: () -> Unit,
    onComplete: (List<String>) -> Unit,
    onDismiss: () -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusRequester = remember { FocusRequester() }
    
    // 状态管理
    var selectedTags by remember { mutableStateOf(initialTags) }
    var inputText by remember { mutableStateOf(TextFieldValue("")) }
    
    // 根据输入内容过滤推荐标签；当 recommendedTags 或输入变化时更新
    val filteredRecommendedTags = remember(inputText.text, recommendedTags) {
        if (inputText.text.isBlank()) {
            recommendedTags
        } else {
            recommendedTags.filter { tag ->
                tag.contains(inputText.text, ignoreCase = true)
            }
        }
    }
    
    Column(
        modifier = modifier
            .fillMaxWidth()
            .height(screenHeight * 0.93f)
            .background(
                color = MaterialTheme.colorScheme.surface,
                shape = RoundedCornerShape(
                    topStart = AppSpacing.cardRadius,
                    topEnd = AppSpacing.cardRadius
                )
            )
            .padding(AppSpacing.cardPadding)
    ) {
        // 标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = AppSpacing.componentMedium),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 取消按钮 - 左端
            Text(
                text = "取消",
                fontSize = AppFontSizes.body,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.clickable { onCancel() }
            )

            // 标题 - 居中
            Text(
                text = title,
                fontSize = AppFontSizes.h4,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center,
                modifier = Modifier.weight(1f)
            )

            // 完成按钮 - 右端
            Text(
                text = "完成",
                fontSize = AppFontSizes.body,
                color = MaterialTheme.colorScheme.primary,
                fontWeight = FontWeight.Medium,
                modifier = Modifier.clickable { onComplete(selectedTags) }
            )
        }

        Spacer(modifier = Modifier.height(AppSpacing.componentLarge))
        
        // 已选择的标签
        if (selectedTags.isNotEmpty()) {
            FlowRow(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppSpacing.componentMedium),
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium)
            ) {
                selectedTags.forEach { tag ->
                    AppChip(
                        text = tag,
                        isSelected = true,
                        showDeleteIcon = true,
                        onClick = {
                            selectedTags = selectedTags.filter { it != tag }
                        },
                        onDeleteClick = {
                            selectedTags = selectedTags.filter { it != tag }
                        }
                    )
                }
            }
        }
        
        // 输入框
        MultiSelectInputField(
            value = inputText,
            onValueChange = { inputText = it },
            placeholder = placeholder,
            focusRequester = focusRequester,
            onTagAdd = { tag ->
                if (tag.isNotBlank() && !selectedTags.contains(tag)) {
                    selectedTags = selectedTags + tag
                    inputText = TextFieldValue("")
                }
            }
        )
        
        Spacer(modifier = Modifier.height(AppSpacing.componentMedium))
        
        // 推荐
        if (filteredRecommendedTags.isNotEmpty()) {
            Text(
                text = "推荐",
                fontSize = AppFontSizes.smallBody,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = AppSpacing.componentSmall)
            )
            
            FlowRow(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState()),
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium)
            ) {
                filteredRecommendedTags.forEach { tag ->
                    AppChip(
                        text = tag,
                        isSelected = selectedTags.contains(tag),
                        onClick = {
                            if (selectedTags.contains(tag)) {
                                selectedTags = selectedTags.filter { it != tag }
                            } else {
                                selectedTags = selectedTags + tag
                            }
                        }
                    )
                }
            }
        }
    }
}


/**
 * 多选输入框
 */
@Composable
private fun MultiSelectInputField(
    value: TextFieldValue,
    onValueChange: (TextFieldValue) -> Unit,
    placeholder: String,
    focusRequester: FocusRequester,
    onTagAdd: (String) -> Unit
) {
    val keyboardController = LocalSoftwareKeyboardController.current
    
    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = Modifier
            .fillMaxWidth()
            .focusRequester(focusRequester)
            .background(
                color = MaterialTheme.colorScheme.surfaceVariant,
                shape = RoundedCornerShape(AppSpacing.componentSmall)
            )
            .padding(horizontal = AppSpacing.componentMedium, vertical = AppSpacing.componentMedium),
        textStyle = TextStyle(
            fontSize = AppFontSizes.body,
            color = MaterialTheme.colorScheme.onSurface
        ),
        cursorBrush = SolidColor(AppColors.Primary),
        keyboardOptions = KeyboardOptions(
            capitalization = KeyboardCapitalization.None,
            autoCorrect = false,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = {
                val tag = value.text.trim()
                if (tag.isNotEmpty()) {
                    onTagAdd(tag)
                }
            }
        ),
        decorationBox = { innerTextField ->
            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.CenterStart
            ) {
                if (value.text.isEmpty()) {
                    Text(
                        text = placeholder,
                        fontSize = AppFontSizes.mediumBody,
                        lineHeight = 16.sp,
                        color = AppColors.InputFieldPlaceholder
                    )
                }
                innerTextField()
            }
        }
    )
}
